package com.douyang.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyang.base.expcetion.UserException;
import com.douyang.base.utils.IdWorkerUtils;
import com.douyang.dto.LoginDTO;
import com.douyang.mapper.UserBaseInfoMapper;
import com.douyang.base.model.UserBaseInfo;
import com.douyang.service.AuthService;
import com.douyang.service.UserBaseInfoService;
import com.douyang.utils.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("email")
public class EmailAuthServiceImpl extends ServiceImpl<UserBaseInfoMapper, UserBaseInfo> implements AuthService {


    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public UserBaseInfo execute(LoginDTO loginDTO) {
        String email = loginDTO.getEmail();
        String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
        Pattern pattern = Pattern.compile(emailPattern);
        Matcher matcher = pattern.matcher(email);
        if(!matcher.matches())throw new UserException("请输入正确邮箱");
        String code = loginDTO.getCode();
        if(StringUtils.isEmpty(code) || code.length()!=4)throw new UserException("请输入正确的验证码");

        String s = stringRedisTemplate.opsForValue().get("code:" + email);
        if(StringUtils.isEmpty(s))throw new UserException("验证码已过期");
        if(!s.equals(loginDTO.getCode()))throw  new UserException("验证码错误");

        UserBaseInfo userBaseInfo = lambdaQuery().eq(UserBaseInfo::getEmail, email).one();
        if(userBaseInfo==null){
            userBaseInfo = new UserBaseInfo();
            userBaseInfo.setUserName("抖阳_"+ UUID.randomUUID().toString().substring(0,8));
            userBaseInfo.setEmail(email);
            userBaseInfo.setClientId(IdWorkerUtils.getInstance().nextId());
            userBaseInfo.setAvatar("1.png");
            save(userBaseInfo);
        }


        return userBaseInfo;
    }
}
